package de.tabuma.shopping.logik;

import de.tabuma.shopping.entity.*;
import java.util.*;

/**
 *
 * @author alefen
 */
public class LicenseUseFacade {
    public static void create(int assignmentId, String information, int methodId, int licenseType, String user) throws Exception {

        List<LicenseAssignment> laList = LicenseAssignmentFacade.getList(assignmentId, licenseType);
        for(int i=0;i<laList.size();i++) {
            LicenseAssignment la = laList.get(i);
            if(la.getLicenseCount()>la.getLicenseUsed()) {
                LicenseUse lu = new LicenseUse();
                lu.setDate(Calendar.getInstance().getTime());
                lu.setLicenseAssignmentId(la.getId().intValue());
                lu.setMethodId(methodId);
                lu.setUseInformation(information);
                PMF.doCreate(lu, user);
                la.setLicenseUsed(la.getLicenseUsed()+1);
                LicenseAssignmentFacade.update(la, user);
                return;
            }
        }

        throw new Exception("No unused license found.");
    }

    public static List<LicenseUse> getList(int licenseAssignmentId) {
        String keys[] = {"licenseAssignmentId"};
        String values[] = {""+licenseAssignmentId};
        return PMF.get(keys, values, new LicenseUse());
    }
}
